﻿using System;
using System.Collections.Generic;
using System.Text;

using System.Runtime.InteropServices;
using Microsoft.Win32;
using System.ComponentModel;

namespace MyAddin
{

    [Guid("B7456C38-4857-4293-972C-6173EA25F9DD")]
    [ComVisible(true)]
    public interface IUDF{
        [Description("Description of my function.")]
        double MyFunction(double value);
    }


    [Guid("9AD16067-19AA-4A16-B20B-0284267972B3")]
    [ComVisible(true), ComDefaultInterface(typeof(IUDF)), ClassInterface(ClassInterfaceType.None)]
    public class UDF : IUDF
    {

        public UDF(){

        }

        private static string GetSubKeyName(Type type, string subKeyName)
        {
            System.Text.StringBuilder s = new System.Text.StringBuilder();
            s.Append(@"CLSID\{");
            s.Append(type.GUID.ToString().ToUpper());
            s.Append(@"}\");
            s.Append(subKeyName);
            return s.ToString();
        }
        
        public double MyFunction(double value)
        {
            return value * 2;
        }

        [ComRegisterFunctionAttribute]
        public static void RegisterFunction(Type t){
            string strkey = GetCLSIDKey(t);
            Registry.ClassesRoot.CreateSubKey(strkey + "Programmable");
            RegistryKey key = Registry.ClassesRoot.OpenSubKey(strkey + "InprocServer32", true);
            key.SetValue("", System.Environment.SystemDirectory + @"\mscoree.dll", RegistryValueKind.String);
            key.Close();
        }

        [ComUnregisterFunctionAttribute]
        public static void UnregisterFunction(Type t){
            Microsoft.Win32.Registry.ClassesRoot.DeleteSubKey(GetCLSIDKey(t) + "Programmable");
        }

        private static string GetCLSIDKey(Type t){
            return @"CLSID\{" + t.GUID.ToString().ToUpper() + @"}\";
        }
    }

}
